#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

""" Overlaps the time stepper to handle the liner complementary problem. """

from DirichletTimeStepper import DirichletTimeStepper
from SorSolvers import Sor


class AmericanTimeStepper(DirichletTimeStepper):
    """ time stepper for american options under gbm. """

    __slots__ = ['m_constraint', 'm_solver']

    def __init__(self, method='cn'):
        """ call the selected constraint linear solver """

        DirichletTimeStepper.__init__(self, method)
        self.m_constraint = None
        self.m_solver = None

    def set_constraint(self, constraint):
        """ set the constraint to be applied by the linear solver. """

        self.m_constraint = constraint

    def _init_engine(self):
        """ set up matrices base on shape functions and linear solver. """

        if self.m_solver is None:
            assert self.m_constraint is not None

            impl_mat = self.get_impl_mat()
            assert impl_mat is not None
            self.m_solver = Sor(impl_mat, self.m_constraint.copy(),
                                'pSor', 1.3, self.m_constraint)

            if 5 == self.get_mat_structure():
                self.m_solver.set_mat_attrib('Penta')

            if 3 == self.get_mat_structure():
                self.m_solver.set_mat_attrib('Tridia')

    def _solve_fwd(self, rhs):
        """ this method overloads a virtual method in the base class.
            it is called from the cranck-nicolson engine. """

        self.m_solver.set_rhs(rhs)
        self.m_solver.solve()
        return self.m_solver.solution()


